import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/image.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:fate_blind_box/widget/date_picker/flutter_datetime_picker.dart';
import 'package:fate_blind_box/widget/date_picker/src/date_format.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

import '../../utils/date.dart';
import '../../widget/icon_text.dart';

class CycleDetailUi extends StatelessWidget {

  final data;

  const CycleDetailUi({Key? key, required this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _CycleDetailWidget(data);
  }
}

class _CycleDetailWidget extends StatefulWidget {

  final data;
  const _CycleDetailWidget(this.data, {Key? key}) : super(key: key);

  @override
  State<_CycleDetailWidget> createState() => _CycleDetailWidgetState();
}

class _CycleDetailWidgetState extends State<_CycleDetailWidget> {
  String _memberId = "";
  String _moodId = "";
  late ScrollController _scrollController;
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _memberId = widget.data['memberId']??"";
    _moodId = widget.data['pid']??"";
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 20 && !_isLoadingMore) {
        if (_pageNum >= 0) {
          _isLoadingMore = true;
          _pageNum++;
          _getComments();
        }
      }
    });
    _getComments();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          "帖子详情",
          style: TextStyle(color: ThemeColor.textColor, fontSize: 16),
        ),
        elevation: 1,
        centerTitle: true,
        leading: const BackButton(color: Colors.black),
      ),
      // body: Stack(
      //   children: [_buildListView(), _buildInputView()],
      // ),
      body: _buildListView(),
    );
  }

  final _comments = <dynamic>[];
  Widget _buildListView() {
    return ListView.builder(
      controller: _scrollController,
      itemCount: _comments.length + 2,
      itemBuilder: (context, index) {
        if (index == 0) return _buildContent();
          if (index == _comments.length + 1) return const SizedBox(height: 96,);
          return _buildItemView(_comments[index - 1], index - 1);
      });
  }

  /// 详情信息
  Widget _buildContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 12,),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(width: 12,),
            ClipRRect(
              borderRadius: BorderRadius.circular(20),
              child: AppImages.avatar(widget.data['profilePhoto'], 40),
            ),
            const SizedBox(width: 12,),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.data['nickName']??"匿名用户",
                  style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
                ),
                const SizedBox(height: 4,),
                Text(
                  _parseDate(widget.data['createTime']??""),
                  style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
                ),
                const SizedBox(height: 8,),
                Text(
                  widget.data["content"]??"",
                  style: TextStyle(fontSize: 12, color: ThemeColor.textColor3),
                )
              ],
            )),
            const SizedBox(width: 12,)
          ],
        ),
        const SizedBox(height: 12,),
        SizedBox(
          height: 230,
          child: _buildBanner(),
        ),
        const SizedBox(height: 12,),
        _buildActions(),
        Container(
          margin: const EdgeInsets.only(left: 12),
          child: Text(
            "热门评论",
            style: TextStyle(fontSize: 16, color: ThemeColor.textColor),
          ),
        )
      ],
    );
  }

  String _parseDate(String date) {
    if (date.isEmpty) return "";
    // final dateTime = DateTime.parse(date);
    // return formatDate(dateTime, ['mm', '-', 'dd', ' ', 'hh', ':', 'mm'], LocaleType.zh);
    return RelativeDateFormat.format(DateTime.parse(date));
  }

  /// 喜欢、评论
  Widget _buildActions() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Expanded(child: Container()),
        GestureDetector(
          onTap: () { _moodThumb("0", widget.data['isLike'] == 1 ? 0 : 1, -1); },
          child: IconText(
            "  ${widget.data['likeCount']??0}",
            icon: Icon(
              Icons.favorite, //favorite_outline
              color: widget.data['isLike'] == 1 ? ThemeColor.mainColor : ThemeColor.textColorSecond,
              size: 18,
            ),
            style: TextStyle(
              color: ThemeColor.textColorSecond,
              fontSize: 13,
            ),
          ),
        ),
        const SizedBox(
          width: 20,
        ),
        GestureDetector(
          onTap: () async {
            await _showInputPopup("");
          },
          child: IconText(
            "  ${widget.data['commentCount']??0}",
            style: TextStyle(
              color: ThemeColor.textColorSecond,
              fontSize: 13,
            ),
            icon: Icon(
              Icons.comment_outlined,
              color: ThemeColor.textColorSecond,
              size: 18,
            ),
          ),
        ),
        const SizedBox(
          width: 12,
        )
      ],
    );
  }

  /// 轮播图
  Widget _buildBanner() {
    List<String> imgList = widget.data['picUrls']?.toString().split(",")??[];
    if (imgList.isEmpty) {
      return Container();
    }
    print(imgList );
    imgList.removeWhere((element) => element.isEmpty);
    return Swiper(
      itemCount: imgList.length,
      itemBuilder: (BuildContext context, int index) {
        return Container(
            margin: const EdgeInsets.symmetric(horizontal: 12),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network(
                imgList[index],
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return _getErrorBuilder(double.infinity, double.infinity);
                },
              ),
            ));
      },
      //分页指示器
      // pagination: SwiperCustomPagination(
      //     builder: (BuildContext context, SwiperPluginConfig config) {
      //   return Container(
      //         alignment: Alignment.bottomCenter,
      //         margin: const EdgeInsets.only(bottom: 12),
      //         child: PageIndicator(
      //           layout: PageIndicatorLayout.SLIDE,
      //           size: 10.0,
      //           space: 10.0,
      //           activeColor: ThemeColor.mainColor,
      //           count: config.itemCount,
      //           color: Colors.black12,
      //           controller: config.pageController
      //         ),
      //       );
      //     }
      // ),
      //页面上的左右箭头
      control: null,
      //自动轮播
      autoplay: false,
      loop: false,
    );
  }

  Widget _getErrorBuilder(double width, double height) {
    return Container(
      width: width,
      height: height,
      decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(4)
          ),
          color: const Color(0xFFF2F2F2)
      ),
      alignment: Alignment.center,
      child: Image.asset(
        "images/ic_error_place.png",
        width: width * 0.5,
        height: height * 0.5,
      ) ,
    );
  }

  /// 评论ITEM
  Widget _buildItemView(data, position) {
    return Container(
      margin: const EdgeInsets.only(top: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(
            width: 12,
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(20),
            child: AppImages.avatar(data['profilePhoto'], 40),
          ),
          Expanded(child: Stack(
            children: [
              Positioned(
                right: 12,
                top: 8,
                child: GestureDetector(
                  onTap: () {
                      _moodThumb(data['id'].toString(), data['isLike'] == 1 ? 0 : 1, position);
                  },
                  child: IconText("  ${data['likeCount']??0}",
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColor.textColorSecond,
                      ),
                      icon: Icon(
                        Icons.favorite,
                        color: data['isLike'] == 1 ? ThemeColor.mainColor : ThemeColor.textColorSecond,
                        size: 16,
                      )),
                )
              ),
              Container(
                padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                            width: 1,
                            color: ThemeColor.dividerColor
                        )
                    )
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(data["nickName"]??"匿名用户", style: TextStyle(color: ThemeColor.textColor, fontSize: 12),),
                    const SizedBox(height: 4,),
                    Text(RelativeDateFormat.format(DateTime.parse(data['createTime'])), style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 12),),
                    const SizedBox(height: 8,),
                    Text(
                      data["content"]??"",
                      style: TextStyle(color: ThemeColor.textColor3, fontSize: 12),
                    ),
                    // const SizedBox(height: 12,),
                    // Text.rich(TextSpan(
                    //   style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
                    //   children: [
                    //     const TextSpan(text: "回复",),
                    //     TextSpan(
                    //       text: "  这是一个昵称",
                    //       style: TextStyle(
                    //           color: ThemeColor.mainColor,
                    //           fontSize: 12
                    //       )
                    //     ),
                    //     TextSpan(
                    //       text: "：哈哈哈哈哈",
                    //       recognizer: TapGestureRecognizer()..onTap = () async {
                    //         await   _showInputPopup("");
                    //       }
                    //     )
                    //   ]
                    // ))
                  ],
                ),
              )
            ],
          ))
        ],
      ),
    );
  }

  /// 输入框
  final FocusNode _inputFocusNode = FocusNode();
  _showInputPopup(String commentId) async {
    return showModalBottomSheet<String>(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (ctx) {
          final controller = TextEditingController();
          return AnimatedPadding(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom
            ),
            duration: Duration.zero,
            child: Container(
              height: 70,
              decoration: const BoxDecoration(color: Colors.white, boxShadow: [
                BoxShadow(
                    color: Colors.black12,
                    offset: Offset(0.0, -4.0), //阴影xy轴偏移量
                    blurRadius: 8.0, //阴影模糊程度
                    spreadRadius: .5 //阴影扩散程度
                )
              ]),
              alignment: Alignment.bottomCenter,
              padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
              child: TextField(
                focusNode: _inputFocusNode,
                controller: controller,
                keyboardType: TextInputType.text,
                cursorColor: ThemeColor.mainColor,
                style: TextStyle(
                    color: ThemeColor.textColor,
                    fontSize: 14
                ),
                textInputAction: TextInputAction.send,
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(24),
                      borderSide: BorderSide(color: ThemeColor.mainColor)
                  ),
                  focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(24),
                      borderSide: BorderSide(color: ThemeColor.mainColor, width: 2)
                  ),
                  fillColor: Colors.red,
                  hintText: "请输入评论",
                  hintStyle: TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
                ),
                onSubmitted: (value) {
                  _commentMood(value, commentId);
                  controller.text = "";
                  Navigator.of(context).pop(value);
                },
              ),
            ),
          );
        }
    );
  }

  /// 获取评论  小于0 代表最后一页
  int _pageNum = 1;
  _getComments() async {
    final res = await Api.getInstance().getMoodComments(_memberId, _moodId, _pageNum, 20);
    if (res['code'] == 0) {
      if (res['data'] != null && res['data']['list'].length > 0) {
        _comments.addAll(res['data']['list']);
        if(res['data']['isLastPage']) {
          _pageNum = -1;
        }
        setState(() {});
      }
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
    _isLoadingMore = false;
  }

  /// 评论圈子
  _commentMood(String content, commentId) async {
    final res = await Api.getInstance().commentMood(commentId, content, _memberId, _moodId);
    if (res['code'] == 0) {
      _comments.insert(0, {
        "memberId": Provider.memberId,
        "nickName": widget.data['nickName'],
        "profilePhoto": widget.data['profilePhoto'],
        "createTime": DateTime.now().toString().substring(0, 19),
        "content": content,
        "likeCount": 0,

      });
      setState(() {});
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  /// 圈子点赞
  /// params: flag 1-点赞，0-取消点赞
  _moodThumb(String commentId, int flag, int position) async {
    final res = await Api.getInstance().moodThumb(commentId, _memberId, _moodId, flag);
    if (res['code'] == 0) {
      if (position < 0) {
        widget.data['likeCount'] += (flag == 1 ? 1 : -1);
        widget.data['isLike'] = flag;
      } else {
        _comments[position]['likeCount'] += (flag == 1 ? 1 : -1);
        _comments[position]['isLike'] = flag;
      }
      setState(() {});
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }
}
